package common.concurrency.baeldung.completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author zhang hao dong
 * @date 2025-06-03 10:58
 * <a href="https://www.baeldung.com/java-completablefuture">...</a>
 */
public class Guide {
    /**
     * boolean complete(V value)
     * 手动完成 Future 并获取结果
     */
    public static void testComplete() throws InterruptedException, ExecutionException {
        CompletableFuture<String> future = new CompletableFuture<>();
        future.complete("Hello World");
        System.out.println(future.get());
    }

    public static void testRunAsync() {
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            System.out.println("记录日志或者发送通知，但不返回任何内容");
        });
        //future.join();
    }

    public static void testSupplyAsync() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello from supplyAsync");
        System.out.println(future.get());
    }

    public static void testThenApply() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello from supplyAsync");
        CompletableFuture<String> thenApply = future.thenApply(s -> s + " from thenApply");
        System.out.println(thenApply.get());
    }

    public static void testThenAccept() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello from supplyAsync");
        CompletableFuture<Void> thenAccept = future.thenAccept(System.out::println);
        System.out.println(thenAccept.get());
    }


    public static void testThenRun() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello from supplyAsync");
        CompletableFuture<Void> thenRun = future.thenRun(System.out::println);
        System.out.println(thenRun.get());
    }

    public static void testThenCompose() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "Hello from supplyAsync")
                .thenCompose(s -> CompletableFuture.supplyAsync(() -> s + " from thenCompose"));
        System.out.println(future.get());
    }


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        testThenCompose();
    }
}
